package com.woniuxy.goods.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.woniuxy.core.util.ObjectCoverUtil;
import com.woniuxy.core.util.StateNum;
import com.woniuxy.goods.client.AdminFeignClient;
import com.woniuxy.goods.dto.AccountDto;
import com.woniuxy.goods.dto.AdminAccountPageDto;
import com.woniuxy.goods.dto.GoodsDto;
import com.woniuxy.goods.dto.ShopDto;
import com.woniuxy.goods.entity.Goods;
import com.woniuxy.goods.entity.ProcessExecute;
import com.woniuxy.goods.entity.ProcessModel;
import com.woniuxy.goods.mapper.ProcessExecuteMapper;
import com.woniuxy.goods.param.AddExecuteParam;
import com.woniuxy.goods.param.FindGoodsPageParam;
import com.woniuxy.goods.service.GoodsService;
import com.woniuxy.goods.service.ProcessExecuteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.goods.service.ProcessModelService;
import com.woniuxy.openfeign.util.Result;
import com.woniuxy.redis.util.RedisKey;
import com.woniuxy.redis.util.RedisUtil;
import com.woniuxy.web.util.ConvertUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.aspectj.weaver.ast.Var;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.xml.bind.annotation.W3CDomHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 * 流程执行记录服务层实现类
 * @author ...
 * @since 2024年05月22日
 */
@Service
public class ProcessExecuteServiceImpl extends ServiceImpl<ProcessExecuteMapper, ProcessExecute> implements ProcessExecuteService {
    /**
     * 典当物品管理服务层接口
     */
    @Resource
    private GoodsService goodsService;
    /**
     * 调用管理模块接口
     */
    @Resource
    private AdminFeignClient adminFeignClient;
    /**
     * 流程模版服务层接口
     */
    @Resource
    private ProcessModelService modelService;
    /**
     * redis工具类
     */
    @Resource
    private RedisUtil redisUtil;


    /**
     * 新增一系列流程
     * @param param 新增流程执行记录对象
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public List<ProcessExecute> addExecute(AddExecuteParam param) throws Exception {
        Goods goods = goodsService.findById(param.getGoodsId());
        if (goods==null||goods.getProcessExecuteId()!= StateNum.GOODS_PROCESS_NOT_APPR) throw new Exception("物品异常");
        Result result2 = adminFeignClient.selectAccountByAdminName(goods.getInputUser());
        if (result2.getCode()!=200) throw new Exception(result2.getMessage());
        AccountDto accountDto = ObjectCoverUtil.castT(result2.getData(), AccountDto.class);
        Result result = adminFeignClient.selectPawnShopById(param.getShopId());
        if (result.getCode()!=200) throw new Exception(result.getMessage());
        ShopDto shopDto = ObjectCoverUtil.castT(result.getData(), ShopDto.class);
        if (shopDto==null||shopDto.getState()!=StateNum.SHOP_STATE_NORMAL) throw new Exception("门店异常");
        Result result1 = adminFeignClient.findAdminInfoByAccountId(shopDto.getShopBossId());
        if (result1.getCode()!=200) throw new Exception("查询管理员异常");
        AccountDto shopAccount = ObjectCoverUtil.castT(result1.getData(), AccountDto.class);
        System.out.println(shopAccount);
        if (shopAccount==null||shopAccount.getState()!=StateNum.ACCOUNT_STATE_NORMAL) throw new Exception("店长异常");
        List<ProcessModel> models = modelService.findModelByProcessId(1);
        List<ProcessExecute> executes = new ArrayList<>();
        for (ProcessModel model : models) {
            ProcessExecute execute = new ProcessExecute();
            execute.setStateName(model.getStateName());
            execute.setStateNum(model.getStateNum());
            execute.setGoodsId(param.getGoodsId());
            execute.setShopId(shopDto.getShopId());
            execute.setIsActive(StateNum.GOODS_IS_NOT_ACTIVE);
            if (model.getStateNum()==StateNum.GOODS_PROCESS_NOT_APPR){
                //获取鉴定师（根据待办最少）
                Object o = redisUtil.zrange(RedisKey.jiandingshi(), 0, 0).toArray()[0];
                System.out.println(o);
                int apprId = Integer.parseInt(o.toString());
                Result adminResult = adminFeignClient.findAdminInfoByAccountId(apprId);
                if (adminResult.getCode()!=200) throw new Exception(adminResult.getMessage());
                AccountDto appr = ObjectCoverUtil.castT(adminResult.getData(), AccountDto.class);
                if (appr==null||appr.getState()!=StateNum.ACCOUNT_STATE_NORMAL) throw new Exception("鉴定师异常");
                execute.setAccountId(apprId);
                execute.setIsActive(StateNum.GOODS_IS_ACTIVE);
                redisUtil.zincrby(RedisKey.jiandingshi(),apprId+"",1);
            } else if (model.getStateNum()==StateNum.GOODS_PROCESS_NOT_EVAL) {
                //获取评估师（根据待办最少）
                Object o = redisUtil.zrange(RedisKey.pinggushi(), 0, 0).toArray()[0];
                System.out.println(o);
                int evalId = Integer.parseInt(o.toString());
                Result adminResult = adminFeignClient.findAdminInfoByAccountId(evalId);
                if (adminResult.getCode()!=200) throw new Exception(adminResult.getMessage());
                AccountDto eval = ObjectCoverUtil.castT(adminResult.getData(), AccountDto.class);
                if (eval==null||eval.getState()!=StateNum.ACCOUNT_STATE_NORMAL) throw new Exception("鉴定师异常");
                execute.setAccountId(evalId);
                redisUtil.zincrby(RedisKey.pinggushi(),evalId+"",1);
            } else if (model.getStateNum()==StateNum.GOODS_PROCESS_NOT_STORE) {
                //执行人店长
                execute.setAccountId(shopAccount.getAccountId());
            } else if (model.getStateNum()==StateNum.GOODS_PROCESS_NOT_OVERALL) {
                //录取人完善信息
                execute.setAccountId(accountDto.getAccountId());
            }
            executes.add(execute);
        }
        saveBatch(executes);
        return executes;
    }

    /**
     * 根据流程执行id修改单个流程活跃状态
     * @param processExecuteId 流程执行id
     * @return 流程执行对象
     * @throws Exception
     */
    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public ProcessExecute updateActiveById(Integer processExecuteId) throws Exception {
        ProcessExecute execute = getById(processExecuteId);
        if (execute==null||execute.getIsActive()!=StateNum.GOODS_IS_ACTIVE) throw new Exception("流程执行记录异常");
        execute.setIsActive(StateNum.GOODS_IS_NOT_ACTIVE);
        updateById(execute);
        return execute;
    }

    /**
     * 流程向下一级活跃
     * @param processExecuteId 流程执行id
     * @return 流程执行对象
     * @throws Exception
     */
    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public ProcessExecute updateUpActiveById(Integer processExecuteId) throws Exception {
        ProcessExecute execute = getById(processExecuteId);
        if (execute==null||execute.getIsActive()!=StateNum.GOODS_IS_ACTIVE) throw new Exception("流程执行记录异常");
        execute.setIsActive(StateNum.GOODS_IS_NOT_ACTIVE);
        updateById(execute);
        if (execute.getStateNum()!=StateNum.GOODS_PROCESS_STORED){
            QueryWrapper<ProcessExecute> wrapper = new QueryWrapper<>();
            wrapper.eq("goods_id",execute.getGoodsId());
            wrapper.eq("state_num",execute.getStateNum()+1);
            ProcessExecute one = getOne(wrapper);
            if (one==null||one.getIsActive()!=StateNum.GOODS_IS_NOT_ACTIVE) throw new Exception("下一流程执行异常");
            one.setIsActive(StateNum.GOODS_IS_ACTIVE);
            updateById(one);
            goodsService.updateGoodsStateNum(one.getGoodsId(),one.getStateNum());
        }
        return execute;
    }

    /**
     * 流程回退一级活跃
     * @param processExecuteId 流程执行id
     * @return 流程执行对象
     * @throws Exception
     */
    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public ProcessExecute updateDownActiveById(Integer processExecuteId) throws Exception {
        ProcessExecute execute = getById(processExecuteId);
        if (execute==null||execute.getIsActive()!=StateNum.GOODS_IS_ACTIVE) throw new Exception("流程执行记录异常");
        execute.setIsActive(StateNum.GOODS_IS_NOT_ACTIVE);
        updateById(execute);
        if (execute.getStateNum()!=StateNum.GOODS_PROCESS_NOT_OVERALL){
            QueryWrapper<ProcessExecute> wrapper = new QueryWrapper<>();
            wrapper.eq("goods_id",execute.getGoodsId());
            wrapper.eq("state_num",execute.getStateNum()-1);
            ProcessExecute one = getOne(wrapper);
            if (one==null||one.getIsActive()!=StateNum.GOODS_IS_NOT_ACTIVE) throw new Exception("上一流程执行异常");
            one.setIsActive(StateNum.GOODS_IS_ACTIVE);
            updateById(one);
            goodsService.updateGoodsStateNum(one.getGoodsId(),one.getStateNum());
        }
        return execute;
    }

    /**
     * 修改指定物品流程
     * @param goodsId 物品id
     * @param processExecuteId 流程执行id
     * @return 流程执行对象
     * @throws Exception
     */
    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public ProcessExecute updateProcessByGoodsId(Integer goodsId, Integer processExecuteId) throws Exception {
        QueryWrapper<ProcessExecute> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",goodsId);
        List<ProcessExecute> list = list(wrapper);
        ProcessExecute processExecute = null;
        for (ProcessExecute execute : list) {
            if (execute.getIsActive()==StateNum.GOODS_IS_ACTIVE){
                if (execute.getStateNum()!=StateNum.GOODS_PROCESS_NOT_STORE){
                    throw new Exception("未处于审核状态");
                }else {
                    execute.setIsActive(StateNum.GOODS_IS_NOT_ACTIVE);
                    updateById(execute);
                }
            }
            if (execute.getStateNum()==processExecuteId){
                execute.setIsActive(StateNum.GOODS_IS_ACTIVE);
                updateById(execute);
                processExecute = execute;
            }
        }
        if (processExecute == null){
            throw new Exception("指定状态流程不存在");
        }
        return processExecute;
    }



    /**
     * 修改账户id对应待办流程
     * @param accountId 账户id
     * @return 流程集合
     * @throws Exception
     */
    @Override
    public List<ProcessExecute> updateProcessByAccountId(Integer accountId) throws Exception {
        Result result = adminFeignClient.loadAllRoleByAccountId1(accountId);
        if (result.getCode()!=200) throw new Exception(result.getMessage());
        System.out.println(result);
        int roleId = Integer.parseInt(result.getData().toString());
        System.out.println(roleId);
        QueryWrapper<ProcessExecute> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",accountId);
        List<ProcessExecute> list = list(wrapper);
        Set<Integer> ids = list.stream().map(o -> o.getProcessExecuteId()).collect(Collectors.toSet());
        if(ObjectUtil.isEmpty(ids)) return null;
        ProcessExecute execute = new ProcessExecute();
        if (roleId==5){
            Object o = redisUtil.zrange(RedisKey.jiandingshi(), 0, 0).toArray()[0];
            int apprId = Integer.parseInt(o.toString());
            execute.setAccountId(apprId);
            redisUtil.zincrby(RedisKey.jiandingshi(),apprId+"",1);
        }else if (roleId==6){
            Object o = redisUtil.zrange(RedisKey.pinggushi(), 0, 0).toArray()[0];
            int surId = Integer.parseInt(o.toString());
            execute.setAccountId(surId);
            redisUtil.zincrby(RedisKey.pinggushi(),surId+"",1);
        }else if(roleId==4){
            Result result1 = adminFeignClient.findShopByAccountId(accountId);
            if (result1.getCode()!=200) throw new Exception(result1.getMessage());
            ShopDto shopDto = ObjectCoverUtil.castT(result1.getData(), ShopDto.class);
            Integer shopId = shopDto.getShopId();
            Result result2 = adminFeignClient.findShopAssistantByShopId(shopId,1);
            if (result2.getCode()!=200) throw new Exception(result2.getMessage());
            List<AdminAccountPageDto> castList = ObjectCoverUtil.castList(result2.getData(), AdminAccountPageDto.class);
            List<Integer> idSet = castList.stream().map(o -> o.getAccountId()).collect(Collectors.toList());
            idSet.remove(accountId);
            System.out.println(idSet);
            if (ObjectUtil.isEmpty(idSet)) throw new Exception("不存在可用店员,无法更换流程执行对象");
            int size = idSet.size();
            int item = new Random().nextInt(size);
            System.out.println(item);
            if (item>0) item = item-1;
            int id = idSet.get(item);
            System.out.println(id);
            execute.setAccountId(id);
        }
        UpdateWrapper<ProcessExecute> wrapper1 = new UpdateWrapper<>();
        wrapper1.in("process_execute_id",ids);
        wrapper1.set("account_id",execute.getAccountId());
        update(wrapper1);
        return null;
    }

    /**
     * 修改店长对应待办流程
     * @param oldAccountId 旧店长id
     * @param newAccountId 新店长id
     * @return 流程集合
     * @throws Exception
     */
    @Override
    public List<ProcessExecute> updateProcessByBoss(Integer oldAccountId, Integer newAccountId) throws Exception {
        Result result = adminFeignClient.findAdminInfoByAccountId(oldAccountId);
        if (result.getCode()!=200) throw new Exception(result.getMessage());
        AccountDto old = ObjectCoverUtil.castT(result.getData(), AccountDto.class);
        Result result1 = adminFeignClient.findAdminInfoByAccountId(newAccountId);
        if (result1.getCode()!=200) throw new Exception(result1.getMessage());
        AccountDto newacc = ObjectCoverUtil.castT(result1.getData(), AccountDto.class);
        if (old==null||newacc==null||newacc.getState()!=StateNum.ACCOUNT_STATE_NORMAL) throw new Exception("账号异常");
        QueryWrapper<ProcessExecute> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",oldAccountId);
        List<ProcessExecute> list = list(wrapper);
        Set<Integer> ids = list.stream().map(o -> o.getProcessExecuteId()).collect(Collectors.toSet());
        UpdateWrapper<ProcessExecute> wrapper1 = new UpdateWrapper<>();
        wrapper1.in("process_execute_id",ids);
        wrapper1.set("account_id",newAccountId);
        update(wrapper1);
        return null;
    }

    /**
     * 根据流程码、商品id查流程
     * @param stateNum 流程码
     * @param goodsId 物品id
     * @return 流程执行对象
     * @throws Exception
     */
    @Override
    public ProcessExecute findExecuteByStateNumGoodsId(Integer stateNum, Integer goodsId) throws Exception {
        QueryWrapper<ProcessExecute> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",goodsId);
        wrapper.eq("state_num",stateNum);
        ProcessExecute one = getOne(wrapper);
        if (one==null) throw new Exception("流程不存在");
        return one;
    }

    /**
     * 根据流程码、管理员id查物品id集合
     * @param stateNum 流程码
     * @param accountId 当前登录管理员id
     * @return 物品id集合
     * @throws Exception
     */
    @Override
    public List<Integer> findGoodsIdsByStateNum(Integer stateNum, Integer accountId) throws Exception {
        Result result = adminFeignClient.findAdminInfoByAccountId(accountId);
        if (result.getCode()!=200) throw new Exception(result.getMessage());
        AccountDto accountDto = ObjectCoverUtil.castT(result.getData(), AccountDto.class);
        if (accountDto==null||accountDto.getState()!=StateNum.ACCOUNT_STATE_NORMAL) throw new Exception("管理员异常");
        QueryWrapper<ProcessExecute> wrapper = new QueryWrapper<>();
        wrapper.eq("state_num",stateNum);
        wrapper.eq("account_id",accountId);
        wrapper.eq("is_active",StateNum.GOODS_IS_ACTIVE);
        List<ProcessExecute> list = list(wrapper);
        List<Integer> goodsIds = list.stream().map(o -> o.getGoodsId()).collect(Collectors.toList());
        return goodsIds;
    }

    @Override
    public List<ProcessExecute> findProcessByGoodsId(Integer goodsId) {
        QueryWrapper<ProcessExecute> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",goodsId);
        return list(wrapper);
    }

    /**
     * 根据账号id查询待办流程
     * @param accountId 携带账号id的请求头
     * @param param 查询物品分页参数
     * @return 物品分页对象
     * @throws Exception
     */
    @Override
    public IPage<GoodsDto> findProcessByAccountId(Integer accountId, FindGoodsPageParam param) throws Exception {
        Result result = adminFeignClient.findAdminInfoByAccountId(accountId);
        if (result.getCode()!=200) throw new Exception(result.getMessage());
        AccountDto accountDto = ObjectCoverUtil.castT(result.getData(), AccountDto.class);
        if (accountDto==null||accountDto.getState()!=StateNum.ACCOUNT_STATE_NORMAL) throw new Exception("管理员异常");
        QueryWrapper<ProcessExecute> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",accountId);
        wrapper.eq("is_active",StateNum.GOODS_IS_ACTIVE);
        List<ProcessExecute> list = list(wrapper);
        Set<Integer> goodsIds = list.stream().map(o -> o.getGoodsId()).collect(Collectors.toSet());
        if (ObjectUtil.isNotEmpty(goodsIds)){
            param.setGoodsIds(goodsIds);
            IPage<GoodsDto> iPage = goodsService.findGoodsPage(param);
            return iPage;
        }
        return null;
    }
}
